import { defineStore } from "pinia";
import { store } from "@/store";
import { ref } from "vue";
import { HMI_LCD_CONTRAST_API } from "@/api/hmi/lcd-contrast.api";
import type {
  LcdContrastInfo,
  LcdContrastUpdateRequest,
  LcdContrastUpdateResponse,
} from "@/api/hmi/lcd-contrast.api";

/**
 * 液晶对比度 Store
 */
export const useLcdContrastStore = defineStore("lcdContrast", () => {
  // 响应式状态
  const currentContrast = ref<number>(0);
  const isLoading = ref<boolean>(false);
  const isUpdating = ref<boolean>(false);
  const isReady = ref<boolean>(false);
  const lastUpdateResult = ref<LcdContrastUpdateResponse | null>(null);

  // 获取当前对比度值
  const getCurrentContrast = () => {
    return currentContrast.value;
  };

  // 设置函数
  const setCurrentContrast = (contrast: number) => {
    currentContrast.value = contrast;
    isReady.value = true;
  };

  // 重置状态
  const resetLcdContrastState = () => {
    currentContrast.value = 0;
    isLoading.value = false;
    isUpdating.value = false;
    isReady.value = false;
    lastUpdateResult.value = null;
  };

  // 重置更新结果
  const resetUpdateResult = () => {
    lastUpdateResult.value = null;
  };

  // API 调用函数
  const fetchLcdContrast = (cpu: number = 1) => {
    return new Promise<LcdContrastInfo[]>((resolve, reject) => {
      isLoading.value = true;

      HMI_LCD_CONTRAST_API.fetchLcdContrast(cpu)
        .then((res) => {
          console.log("fetchLcdContrast res:", res);

          // 设置对比度值
          if (res && res.length > 0 && typeof res[0].Contrast === "number") {
            setCurrentContrast(res[0].Contrast);
          }

          resolve(res);
        })
        .catch((error) => {
          console.error("fetchLcdContrast error:", error);
          reject(error);
        })
        .finally(() => {
          isLoading.value = false;
        });
    });
  };

  const updateLcdContrast = (cpu: number = 1, contrast: number) => {
    return new Promise<LcdContrastUpdateResponse>((resolve, reject) => {
      // 验证对比度值范围
      if (contrast < 0 || contrast > 100) {
        const error = new Error("对比度值必须在0到100之间");
        reject(error);
        return;
      }

      isUpdating.value = true;
      lastUpdateResult.value = null;

      const updateData: LcdContrastUpdateRequest[] = [{ contrast: contrast }];

      HMI_LCD_CONTRAST_API.updateLcdContrast(cpu, updateData)
        .then((res) => {
          console.log("updateLcdContrast res:", res);

          lastUpdateResult.value = res;

          // 更新成功后重新获取最新数据
          if ("status" in res && res.status === "Success") {
            setCurrentContrast(contrast);
            // 可选：重新获取服务器数据确保同步
            fetchLcdContrast(cpu).catch(() => {});
          }

          resolve(res);
        })
        .catch((error) => {
          console.error("updateLcdContrast error:", error);
          lastUpdateResult.value = {
            error: error.message || "更新失败",
            message: error.message || "液晶对比度更新失败",
            code: error.code || -1,
          };
          reject(error);
        })
        .finally(() => {
          isUpdating.value = false;
        });
    });
  };

  // 验证对比度值
  const validateContrast = (contrast: number) => {
    const errors: string[] = [];

    if (typeof contrast !== "number") {
      errors.push("对比度值必须是数字");
    } else {
      if (contrast < 0) {
        errors.push("对比度值不能小于0");
      }
      if (contrast > 100) {
        errors.push("对比度值不能大于100");
      }
      if (!Number.isInteger(contrast)) {
        errors.push("对比度值必须是整数");
      }
    }

    return {
      isValid: errors.length === 0,
      errors,
    };
  };

  return {
    // 状态
    currentContrast,
    isLoading,
    isUpdating,
    isReady,
    lastUpdateResult,

    // 方法
    getCurrentContrast,
    setCurrentContrast,
    resetLcdContrastState,
    resetUpdateResult,
    fetchLcdContrast,
    updateLcdContrast,
    validateContrast,
  };
});

/**
 * 适用于 setup 之外的场景
 */
export function useLcdContrastStoreHook() {
  return useLcdContrastStore(store);
}
